//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.tuliu.appupdate.updatelib;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.text.TextUtils;
import android.util.AndroidRuntimeException;
import android.util.Log;

import com.tuliu.appupdate.crash.CrashReportManager;
import com.tuliu.appupdate.crash.MyCrashHandler;

import org.json.JSONObject;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author liaoyong
 * @desc 功能描述
 * @date 2016/4/11 13:57
 */
public class CheckUpdateService extends MultiIntentService {
    private static final String EXTRA_AUTO_DOWNLOAD = "AutoDownload";
    private static final String EXTRA_AUTO_SHOW_DIALOG_OR_NOTIFICATION = "autoShowDialogOrNotification";
    private static final String EXTRA_NOTIFICATION = "notification";
    private static final String EXTRA_RESULT_RECEIVER = "ResultReceiver";
    private static final String TAG = "CheckUpdateService";
    static final String ACTION_INSTALL_OR_OPEN_APPSTORE = "com.qihoo.checkupdate.sdk.ACTION_INSTALL_OR_OPEN_APPSTORE";
    private static final String ACTION_DOWNLOAD = "com.qihoo.checkupdate.sdk.ACTION_DOWNLOAD";
    private static final String ACTION_CHECKUPDATE = "com.qihoo.checkupdate.sdk.ACTION_CHECKUPDATE";
    private static final String ACTION_START_APPSTORE = "com.qihoo.checkupdate.sdk.ACTION_START_APPSTORE";
    private static AtomicBoolean sIsDownloading = new AtomicBoolean(false);
    private CrashReportManager mCrashReportManager;

    public CheckUpdateService() {
        super(TAG);
    }

    public void onCreate() {
        super.onCreate();
        MyCrashHandler.getInstance().register(this.getApplicationContext());
        this.mCrashReportManager = new CrashReportManager(this.getApplicationContext());
        this.mCrashReportManager.postCrashFile();
    }

    public void onDestroy() {
        if(this.mCrashReportManager != null) {
            this.mCrashReportManager.cancel();
        }

        super.onDestroy();
    }

    protected void onHandleIntent(Intent intent) {
        String action = intent.getAction();
        if(ACTION_START_APPSTORE.equals(action)) {
            this.doStartAppStore(intent);
        } else if(ACTION_DOWNLOAD.equals(action)) {
            if(sIsDownloading.get()) {
                if(UpdateManager.isDebug()) {
                    Log.d(TAG, "onStart doDownload(intent); downloading. skip");
                }

                return;
            }

            this.doDownload(intent);
        } else if(ACTION_CHECKUPDATE.equals(action)) {
            this.doCheckupdate(intent);
        } else if(ACTION_INSTALL_OR_OPEN_APPSTORE.equals(action)) {
            try {
                this.doNotifyDownloadComplete(intent);
            } catch (Exception var4) {
                var4.printStackTrace();
            }
        } else if(UpdateManager.isDebug()) {
            Log.d(TAG, "onStart intent=" + intent.toUri(0) + ",fail,no action...");
        }

    }

    protected void doNotifyDownloadComplete(Intent intent) {
        Uri data = intent != null?intent.getData():null;
        String filepath = data != null?data.getPath():null;
        PackageInfo info = filepath != null && (new File(filepath)).exists()?this.getPackageManager().getPackageArchiveInfo(filepath, 0):null;
        DownloadInfo downloadInfo;
        if(info != null && "com.qihoo.appstore".equals(info.packageName)) {
            downloadInfo = (DownloadInfo)intent.getParcelableExtra("DownloadInfo");
            AppInfo appInfo = downloadInfo.updateInfo;
            if(downloadInfo != null && appInfo != null) {
                Utils.startAppStoreToUpdate(this, appInfo, appInfo.packageName, !Utils.isMyNewVersion(this, appInfo));
            }
        } else {
            downloadInfo = (DownloadInfo)intent.getParcelableExtra("DownloadInfo");
            if(filepath != null && (new File(filepath)).exists() && downloadInfo != null && info != null && Utils.isMyNewPackage(this, info.packageName, info.versionCode)) {
                try {
                    Intent e = new Intent("android.intent.action.VIEW");
                    e.addFlags(268435456);
                    e.setDataAndType(data, intent.getType());
                    this.startActivity(e);
                } catch (Exception var8) {
                    if(UpdateManager.isDebug()) {
                        var8.printStackTrace();
                    }
                }
            }
        }

    }

    static void startDownload(Context context, DownloadInfo info, ResultReceiver resultReceiver) {
        Intent intent = new Intent(context, CheckUpdateService.class);
        intent.setAction(ACTION_DOWNLOAD);
        intent.putExtra("DownloadInfo", info);
        intent.putExtra(EXTRA_RESULT_RECEIVER, resultReceiver);
        context.startService(intent);
    }

    static void checkUpdate(Context context, String packageName, boolean notification, String checkUrl, ResultReceiver resultReceiver, boolean autoShowDialogOrNotification) {
        Intent intent = new Intent(context, CheckUpdateService.class);
        intent.setAction("com.qihoo.checkupdate.sdk.ACTION_CHECKUPDATE");
        intent.putExtra(EXTRA_NOTIFICATION, notification);
        intent.putExtra(EXTRA_AUTO_SHOW_DIALOG_OR_NOTIFICATION, autoShowDialogOrNotification);
        intent.putExtra("checkUrl", checkUrl);
        if(resultReceiver != null) {
            intent.putExtra(EXTRA_RESULT_RECEIVER, resultReceiver);
        }

        intent.setData(Uri.parse("package:" + packageName));
        context.startService(intent);

        try {
            Intent e = new Intent();
            e.setClassName("com.qihoo.appstore", "com.qihoo.express.mini.service.DaemonCoreService");
            e.putExtra("startType", 2001);
            e.putExtra("start_type_app_package_name", context.getPackageName());
            context.startService(e);
        } catch (Exception var7) {
            ;
        }

    }


    private void doStartAppStore(Intent intent) {
        try {
            Uri e = intent.getData();
            String packageName = e != null?e.getEncodedSchemeSpecificPart():null;
            if(!TextUtils.isEmpty(packageName)) {
                AppInfo info = (AppInfo)intent.getParcelableExtra("UpdateInfo");
                Utils.startAppStoreToUpdate(this, info, packageName, intent.getBooleanExtra(EXTRA_AUTO_DOWNLOAD, true));
            } else if(UpdateManager.isDebug()) {
                Log.e(TAG, "doStartAppStore packagename is null");
            }
        } catch (Exception var5) {
            if(UpdateManager.isDebug()) {
                Log.e(TAG, "doStartAppStore", var5);
            }
        }

    }

    private synchronized void doCheckupdate(Intent intent) {
        ResultReceiver resultReceiver = null;
        if(intent != null) {
            resultReceiver = (ResultReceiver)intent.getParcelableExtra("ResultReceiver");
        }

        byte resultCode = 2;
        Bundle resultData = new Bundle();

        try {
            if(sIsDownloading.get()) {
                if(UpdateManager.isDebug()) {
                    Log.d(TAG, "onStart doCheckupdate downloading. skip");
                }

                return;
            }

            Uri e = intent.getData();
            String sw1 = e != null?e.getEncodedSchemeSpecificPart():null;
            boolean pw1 = intent.getBooleanExtra(EXTRA_NOTIFICATION, false);
            boolean autoShowDialogOrNotification = intent.getBooleanExtra(EXTRA_AUTO_SHOW_DIALOG_OR_NOTIFICATION, true);
            if(!TextUtils.isEmpty(sw1)) {
                String url = "";
                if (intent.hasExtra("checkUrl")) {
                    url = intent.getStringExtra("checkUrl");
                } else {
                    url = Utils.getCheckUpdateUrl(this, sw1);
                }
                String strJson = HttpHelper.get(this, url);
                if(!TextUtils.isEmpty(strJson)) {
                   Object dataJson =  new JSONObject(strJson).get("data");
                    Log.d("update", "liaoyongupdate:" + dataJson.toString());
                    int versionCode = 0;
                    if (url.contains("version_code")) {
                        String[] temps = url.split("=");
                        String tempStr = temps[temps.length - 1];
                        versionCode = Integer.parseInt(tempStr);
                    }

                    AppInfo info = new AppInfo(new JSONObject(dataJson.toString()), versionCode);
                    info.packageName = sw1;
                    resultData.putParcelable("UpdateInfo", info);
                    if(info.isNewVersion && autoShowDialogOrNotification) {
                        if(!pw1) {
                            Intent checkUpdateAcitivtyIntent = new Intent(this, CheckUpdateAcitivty.class);
                            checkUpdateAcitivtyIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            checkUpdateAcitivtyIntent.putExtra("UpdateInfo", info);
                            checkUpdateAcitivtyIntent.putExtra(EXTRA_RESULT_RECEIVER, resultReceiver);
                            this.startActivity(checkUpdateAcitivtyIntent);
                        } else {
                            NotificationHelper.notifyNewUpdate(this, info);
                        }
                    }

                    resultCode = -1;
                } else {
                    if(UpdateManager.isDebug()) {
                        Log.e(TAG, "doCheckupdate HTTP response is null");
                    }
                    resultData.putString(UpdateManager.KEY_ERROR_MSG, "HTTP response is null");
                }
                return;
            }

            if(UpdateManager.isDebug()) {
                Log.w(TAG, "doCheckupdate packageName is null,return");
            }

            resultData.putString(UpdateManager.KEY_ERROR_MSG, "doCheckupdate packageName is null,return");
        } catch (Throwable var23) {
            if(UpdateManager.isDebug()) {
                Log.e(TAG, "doCheckupdate", var23);
            }

            resultCode = 2;
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            var23.printStackTrace(pw);
            resultData.putString(UpdateManager.KEY_ERROR_MSG, sw.toString());
            resultData.putString("Exception", var23.getClass().getName());
            resultData.putString("ExceptionStackTrace", sw.toString());
            return;
        } finally {
            if(resultReceiver != null) {
                try {
                    resultData.putInt(UpdateManager.KEY_ERROR_CODE, resultCode);
                } catch (Exception var22) {
                    ;
                }

                this.sendResult(resultReceiver, 19, resultData);
            }

        }

    }

    private void sendResult(ResultReceiver receiver, int resultCode, Bundle resultData) {
        if(receiver != null) {
            receiver.send(resultCode, resultData);
        }

    }

    private void doDownload(Intent intent) {
        sIsDownloading.set(true);
        final Bundle resultData = new Bundle();
        final ResultReceiver resultReceiver = (ResultReceiver)intent.getParcelableExtra(EXTRA_RESULT_RECEIVER);
        final DownloadInfo info = (DownloadInfo)intent.getParcelableExtra("DownloadInfo");
        if(info != null) {
            resultData.putParcelable("UpdateInfo", info.updateInfo);
        }

        resultData.putAll(intent.getExtras());
        String filepath = info != null?info.file:null;
        if(info != null && !TextUtils.isEmpty(filepath)) {
            File file = new File(filepath);
            byte errorCode = 2;

            try {
                StringWriter sw;
                try {
                    String e = info.downloadUrl;
                    if(!TextUtils.isEmpty(e)) {
                        if(info.showNotification) {
                            NotificationHelper.notifyDownloadProgress(this, info.title, 0L, 0L);
                        }

                        resultData.putLong("progress", 0L);
                        resultData.putLong("max", 0L);
                        this.sendResult(resultReceiver, 17, resultData);
                        sw = null;
                        File sw1;
                        if(!TextUtils.isEmpty(e) && e.equals(info.updateInfo.appStoreDownloadUrl)) {
                            sw1 = new File(Utils.getUpdateTempFile(this, HttpHelper.getReslUrl(this, e)));
                        } else {
                            sw1 = new File(Utils.getUpdateTempFile(this, e));
                        }

                        File pw1 = file.getParentFile();
                        if(!pw1.exists()) {
                            pw1.mkdirs();
                        }

                        if(file.exists()) {
                            file.delete();
                        }

                        String downloadedPath = HttpHelper.get(this, e, sw1, new ProgressListener() {
                            private int mLastProgress = -1;

                            public void onProgressChanged(long progress, long max) {
                                int per = (int)(100.0F * (float)progress / (float)max);
                                if(this.mLastProgress != per) {
                                    if(info.showNotification) {
                                        NotificationHelper.notifyDownloadProgress(CheckUpdateService.this, info.title, progress, max);
                                    }

                                    this.mLastProgress = per;
                                    resultData.putLong("progress", progress);
                                    resultData.putLong("max", max);
                                    CheckUpdateService.this.sendResult(resultReceiver, 18, resultData);
                                }

                            }
                        });
                        File downloadedFile = new File(downloadedPath);
                        downloadedFile.renameTo(file);
                        if(file.exists()) {
                            Process process = Runtime.getRuntime().exec("chmod 755 " + file.getPath());

                            try {
                                process.waitFor();
                            } catch (Exception var31) {
                                ;
                            }

                            process = Runtime.getRuntime().exec("chmod 755 " + file.getParent());

                            try {
                                process.waitFor();
                            } catch (Exception var30) {
                                ;
                            }

                            if(info != null && info.autoInstall) {
                                Utils.installApk(this, file.getPath());
                            } else if(info != null && info.autoInstallAndOpen) {
                                sIsDownloading.set(false);
                                if(info.showNotification) {
                                    NotificationHelper.notifyDownloadComplete(this, info, file);
                                }

                                errorCode = UpdateManager.ERROR_OK ;

                                try {
                                    resultData.putInt(UpdateManager.KEY_ERROR_CODE, errorCode);
                                } catch (Exception var29) {
                                    ;
                                }

                                resultData.putString(UpdateManager.KEY_DOWNLOAD_FILE_PATH, info.file);
                                this.sendResult(resultReceiver, 19, resultData);
                                String detailPackageName = info.updateInfo != null?info.updateInfo.packageName:null;
                                if(installAndWaitComplete(this, file.getPath(), 240000L)) {
                                    Utils.startAppStoreToUpdate(this, info.updateInfo, detailPackageName, true);
                                    boolean errorCode1 = true;
                                }
                            }

                            errorCode = -1;
                        } else {
                            errorCode = 2;
                            resultData.putString(UpdateManager.KEY_ERROR_MSG, "Dest file not exists");
                        }

                        return;
                    }

                    resultData.putString(UpdateManager.KEY_ERROR_MSG, "服务器没有返回下载地址");
                } catch (Throwable var32) {
                    if(file != null) {
                        file.delete();
                    }

                    if(UpdateManager.isDebug()) {
                        Log.e(TAG, "doDownload", var32);
                    }

                    if(info != null && info.autoInstallAndOpen) {
                        if(info.showNotification) {
                            NotificationHelper.notifyDownloadComplete(this, info, file);
                        }

                        try {
                            resultData.putInt(UpdateManager.KEY_ERROR_CODE, errorCode);
                        } catch (Exception var28) {
                            ;
                        }

                        this.sendResult(resultReceiver, 19, resultData);
                    }

                    errorCode = 2;
                    sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    var32.printStackTrace(pw);
                    resultData.putString(UpdateManager.KEY_ERROR_MSG, sw.toString());
                    resultData.putString(UpdateManager.KEY_EXCEPTION_CLASS_NAME, var32.getClass().getName());
                    resultData.putString(UpdateManager.KEY_EXCEPTION_STACK_TRACE, sw.toString());
                    return;
                }
            } finally {
                if(info == null || !info.autoInstallAndOpen) {
                    if(info.showNotification) {
                        NotificationHelper.notifyDownloadComplete(this, info, file);
                    }

                    try {
                        resultData.putInt(UpdateManager.KEY_ERROR_CODE, errorCode);
                    } catch (Exception var27) {
                        ;
                    }

                    resultData.putString(UpdateManager.KEY_DOWNLOAD_FILE_PATH, info.file);
                    this.sendResult(resultReceiver, 19, resultData);
                }

                sIsDownloading.set(false);
            }

        } else {
            resultData.putString(UpdateManager.KEY_ERROR_MSG, "DownloadInfo or file path is null");
        }
    }

    private static boolean installAndWaitComplete(Context context, String file, long timeout) {
        PackageInfo packageArchiveInfo = context.getPackageManager().getPackageArchiveInfo(file, 0);
        if(packageArchiveInfo == null) {
            throw new AndroidRuntimeException("Can not parse the file " + file + " as apk");
        } else {
            final String packageName = packageArchiveInfo.packageName;
            final Object sLock = new Object();
            BroadcastReceiver receiver = new BroadcastReceiver() {
                public void onReceive(Context context, Intent intent) {
                    Object var3 = sLock;
                    synchronized(sLock) {
                        if(packageName.equalsIgnoreCase(intent.getData().getSchemeSpecificPart())) {
                            sLock.notifyAll();

                            try {
                                context.getApplicationContext().unregisterReceiver(this);
                            } catch (Exception var6) {
                                ;
                            }
                        }

                    }
                }
            };
            IntentFilter filter = new IntentFilter("android.intent.action.PACKAGE_ADDED");
            filter.addDataScheme("package");
            context.getApplicationContext().registerReceiver(receiver, filter);
            Utils.installApk(context, file);
            synchronized(sLock) {
                try {
                    sLock.wait(timeout);
                } catch (Throwable var13) {
                    ;
                }
            }

            try {
                context.getApplicationContext().unregisterReceiver(receiver);
            } catch (Throwable var12) {
                ;
            }

            return Utils.isPackageInstalled(context, packageName);
        }
    }
}
